package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.constraintlayout.widget.Group;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.PurchaseRefundAddingAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.GoodsStoreRetreatInfo;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import com.example.sunmiv1.entity.StatusBean;
import com.example.sunmiv1.entity.StoreWarehouseInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


//  採購管理.新增採購退單
public class PurchaseRefundAddingActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.view_bg_top)
    View viewBgTop;
    @BindView(R.id.spinner_warehouse_choose)
    Spinner sprWarehouseChoose;
    @BindView(R.id.spinner_supplies)
    Spinner sprSupplies;
    @BindView(R.id.btn_goods_choose)
    LinearLayout btnGoodsChoose;
    @BindView(R.id.ed_search)
    EditText edSearch;
    @BindView(R.id.iv_search_code)
    ImageView ivSearchCode;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.view_bg_body)
    View viewBgBody;
    @BindView(R.id.tv_order_note)
    TextView tvOrderNote;
    @BindView(R.id.ed_order_note)
    EditText edOrderNote;
    @BindView(R.id.rv_pur_refund_setting)
    RecyclerView rvPurRefundSetting;
    @BindView(R.id.view_bg_footer)
    View viewBgFooter;
    @BindView(R.id.btn_operation)
    Button btnOperation;
    @BindView(R.id.btn_delete)
    Button btnDelete;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.btn_order_commit)
    Button btnOrderCommit;

    private static final int GET_ERROR_STATUS = 1;
    private static final int GET_INFO_STOREWAREHOUSE = 2;
    private static final int REFRESH_VIEW = 3;
    @BindView(R.id.body_group)
    Group bodyGroup;
    @BindView(R.id.group_remark)
    Group groupRemark;
    @BindView(R.id.group_deleteandOk)
    Group groupDeleteandOk;
    @BindView(R.id.btn_all_check)
    Button btnAllCheck;
    @BindView(R.id.btn_all_check_not)
    Button btnAllCheckNot;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;

    private StoreWarehouseInfo storeWarehouseInfo;// 採購倉與供貨商信息 Bean

    private ACache aCache;// 緩存
    private String userType;// 用戶身份

    private List<String> sprWarehouseIdList;    //倉庫id列表
    private List<String> sprWarehouseNameList; // 倉庫名稱列表（左上角spinner）
    private List<String> sprSupplierIdList;    // 供貨商id列表
    private List<String> sprSupplierNameList;  // 供貨商名稱列表（右上角spinner）
    private static ArrayAdapter wSpinnerAdapter; // 倉庫列表spinner適配器
    private static ArrayAdapter sSpinnerAdapter; // 供貨商列表spinner適配器

//    private ArrayList<GoodsStoreRetreatInfo.DataBean> retreatList;

    /* */
    private String mWarehouseId;//spinner中選擇的倉庫
    private String mSupplierId;//spinner中選擇的供應商
    private String this_SupplierId;  //上傳的倉庫
    private String this_WarehouseId; //...
    private String this_Remark;//...
    private ArrayList<GoodsStoreRetreatInfo.DataBean> choiceList;// 退貨訂單列表

    private ArrayList<String> notInIdArr;// 已在此頁的貨物id  添加和選擇2個頁面都要維護這個列表

    private static PurchaseRefundAddingAdapter purchaseRefundAddingAdapter;
    private LoadingDialog loadingDialog;

    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.btn_goods_choose, R.id.iv_search_code, R.id.iv_search, R.id.btn_operation,
            R.id.btn_delete, R.id.btn_ok, R.id.btn_order_commit, R.id.btn_all_check, R.id.btn_all_check_not, R.id.btn_goods_scanFood})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.btn_goods_choose:
                if (mSupplierId != null && mWarehouseId != null) {
                    Intent intent = new Intent(this, PurchaseRefundChooseGoodsActivity.class);
                    intent.putExtra("WarehouseId", mWarehouseId);
                    intent.putExtra("SupplierId", mSupplierId);
                    intent.putStringArrayListExtra("not_in_ids", notInIdArr);
                    startActivityForResult(intent, 100);
                } else {
                    Toast.makeText(this, "請選擇倉庫和供貨商", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_goods_scanFood:
                if (mSupplierId != null && mWarehouseId != null) {
                    scanGood(4, choiceList);
                } else {
                    Toast.makeText(this, "請選擇倉庫和供貨商", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_search_code:
                startQrCode();
                break;
            case R.id.iv_search:
                searchGood(edSearch.getText().toString());
                break;
            case R.id.btn_operation:
                if (choiceList.size() == 0) {
                    Toast.makeText(this, "列表爲空，不能操作", Toast.LENGTH_SHORT).show();
                } else {
                    btnOperation.setVisibility(View.GONE);
                    btnOrderCommit.setVisibility(View.GONE);
                    groupDeleteandOk.setVisibility(View.VISIBLE);
                    btnAllCheck.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_all_check:
                for (GoodsStoreRetreatInfo.DataBean parcelData : choiceList) {
                    parcelData.setChecked(true);
                }
                purchaseRefundAddingAdapter.notifyDataSetChanged();
                btnAllCheck.setVisibility(View.GONE);
                btnAllCheckNot.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_all_check_not:
                for (GoodsStoreRetreatInfo.DataBean parcelData : choiceList) {
                    parcelData.setChecked(false);
                }
                purchaseRefundAddingAdapter.notifyDataSetChanged();
                btnAllCheckNot.setVisibility(View.GONE);
                btnAllCheck.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_delete:
                for (int i = choiceList.size() - 1; i >= 0; i--) {
                    if (choiceList.get(i).isChecked()) {
                        notInIdArr.remove(choiceList.get(i).getId());
                        choiceList.remove(i);
                    }
                }
                purchaseRefundAddingAdapter.notifyDataSetChanged();
                if (choiceList.size() == 0) {
                    sprSupplies.setClickable(true);
                    sprWarehouseChoose.setClickable(true);
                }
                break;
            case R.id.btn_ok:
                btnOrderCommit.setVisibility(View.VISIBLE);
                groupDeleteandOk.setVisibility(View.GONE);
                if (choiceList.size() == 0) {
                    groupRemark.setVisibility(View.GONE);
                }
                btnAllCheckNot.setVisibility(View.GONE);
                btnAllCheck.setVisibility(View.GONE);
                btnOperation.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_order_commit:
                boolean notGreaterThanReNum = false;
                if (choiceList == null || choiceList.size() == 0) {
                    Toast.makeText(this, "列表爲空，不能操作", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (GoodsStoreRetreatInfo.DataBean dataBean : choiceList) {
                    LogUtil.i("data.getRetreat_price():" + dataBean.getRetreat_price() + "   dataBean.getRetreat_num_act():" + dataBean.getRetreat_num_act());
                    if (dataBean.getRetreat_price() == null || dataBean.getRetreat_num_act() == null) {
                        Toast.makeText(this, dataBean.getGoods_name() + "的退貨價和退貨數量不能爲空", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        if (dataBean.getRetreat_price() < 0) {
                            Toast.makeText(this, dataBean.getGoods_name() + "的退貨價不合法", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (dataBean.getSurplus_num() < dataBean.getRetreat_num_act()) {
                            Toast.makeText(this, dataBean.getGoods_name() + "的退貨數量不應該大於庫存", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (dataBean.getRetreat_num_act() <= 0) {
                            Toast.makeText(this, dataBean.getGoods_name() + "的退貨數量輸入不合法", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            notGreaterThanReNum = true;
                        }
                    }
                }
                if (notGreaterThanReNum) {
                    new AlertDialog.Builder(this).setTitle("提示")//設置對話框標題
                            .setMessage("確定要提交退貨？")//設置顯示的內容
                            .setPositiveButton("確定", (dialog, which) -> {//確定按鈕的響應事件
                                postRetreatOrder();
                            }).setNegativeButton("取消", (dialog, which) -> {//取消按鈕的響應事件
                    }).show();//顯示此對話框
                }
                break;
            case R.id.btn_to_top:
                rvPurRefundSetting.smoothScrollToPosition(0);
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_INFO_STOREWAREHOUSE:
                    wSpinnerAdapter.notifyDataSetChanged();
                    sSpinnerAdapter.notifyDataSetChanged();
                    break;
                case GET_ERROR_STATUS:
                    break;
                case REFRESH_VIEW:
                    purchaseRefundAddingAdapter.notifyDataSetChanged();
                    groupRemark.setVisibility(View.GONE);
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_purchase_refund_add);
        ButterKnife.bind(this);
        aCache = ACache.get(this);
        loadingDialog = new LoadingDialog(this);
        userType = aCache.getAsString("userType");
        titleTitle.setText(R.string.purchaseRefundAddingTitle);
        choiceList = new ArrayList<>();
        purchaseRefundAddingAdapter = new PurchaseRefundAddingAdapter(this, choiceList);
        rvPurRefundSetting.setLayoutManager(new LinearLayoutManager(this));
        rvPurRefundSetting.setAdapter(purchaseRefundAddingAdapter);
    }

    @Override
    protected void initData() {
        aCache = ACache.get(this);
        getSupplierAndWarehouseInfo();
        notInIdArr = new ArrayList<>();
        initSpinner();
    }


    @Override
    protected void initListener() {
        purchaseRefundAddingAdapter.setCBListener((isChecked, position) -> {
            choiceList.get(position).setChecked(isChecked);
            if (isChecked) {
                groupDeleteandOk.setVisibility(View.VISIBLE);
                btnOrderCommit.setVisibility(View.GONE);
            }
        });
        purchaseRefundAddingAdapter.setChoose(index -> {
            Intent intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 12);
            intent.putExtra("good", choiceList.get(index));
            startActivityForResult(intent, 200);
        });
        edOrderNote.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                this_Remark = s.toString();
            }
        });
        sprSupplies.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mSupplierId = null;
                } else {
                    mSupplierId = sprSupplierIdList.get(position - 1);
                    aCache.put("supplier_id", mSupplierId);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sprWarehouseChoose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                LogUtil.i("spinner顯示：" + sprWarehouseChoose.getSelectedItem());
                if (position == 0) {
                    mWarehouseId = null;
                } else {
                    mWarehouseId = sprWarehouseIdList.get(position - 1);
                    aCache.put("warehouse_id", mWarehouseId);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    // 初始化spinner
    private void initSpinner() {
        sprWarehouseIdList = new ArrayList<>();
        sprWarehouseNameList = new ArrayList<>();
        sprWarehouseNameList.add("所有倉庫");
        sprWarehouseNameList.add("暫無倉庫");
        sprSupplierNameList = new ArrayList<>();
        sprSupplierIdList = new ArrayList<>();
        sprSupplierNameList.add("所有供貨商");
        sprSupplierNameList.add("暫無供貨商");
        wSpinnerAdapter = new ArrayAdapter(this, R.layout.item_drop, sprWarehouseNameList);
        sprWarehouseChoose.setAdapter(wSpinnerAdapter);
        sSpinnerAdapter = new ArrayAdapter(this, R.layout.item_drop, sprSupplierNameList);
        sprSupplies.setAdapter(sSpinnerAdapter);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.REQ_QR_CODE:
                    Bundle bundle = data.getExtras();
                    edSearch.setText(bundle != null ? bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN) : "");
                    String info = edSearch.getText().toString().trim();
                    searchGoodbyCode(choiceList, info);
                    break;
                case 100://選擇商品返回的數據
                    choiceList.addAll(data.getParcelableArrayListExtra("choice_list"));
                    this_SupplierId = data.getStringExtra("supplier_id");
                    this_WarehouseId = data.getStringExtra("warehouse_id");
                    purchaseRefundAddingAdapter.notifyDataSetChanged();
                    LogUtil.i("intent傳回來的GoodsStoreRetreatInfo.DataBean[]的長度：" + new Gson().toJson(choiceList));
                    for (GoodsStoreRetreatInfo.DataBean parcelData : choiceList) {
                        notInIdArr.add(parcelData.getId());
                        parcelData.setChecked(false);
                        parcelData.setRetreat_price(parcelData.getPurchase_price());
                    }
                    sprWarehouseChoose.setClickable(false);
                    sprSupplies.setClickable(false);
                    break;
                case 110:
                    List<GoodsStoreRetreatInfo.DataBean> s = (List<GoodsStoreRetreatInfo.DataBean>) data.getSerializableExtra("list");
                    for (GoodsStoreRetreatInfo.DataBean dataBean : s) {
                        dataBean.setChecked(false);
                        notInIdArr.add(dataBean.getId());
                        dataBean.setRetreat_price(dataBean.getPurchase_price());
                    }
                    this_SupplierId = aCache.getAsString("supplier_id");
                    this_WarehouseId = aCache.getAsString("warehouse_id");
                    choiceList.clear();
                    choiceList.addAll(s);
                    purchaseRefundAddingAdapter.notifyDataSetChanged();
                    break;
                case 200:
                    GoodsStoreRetreatInfo.DataBean bean = (GoodsStoreRetreatInfo.DataBean) data.getSerializableExtra("bean");
                    int index = 0;
                    for (int t = 0; t < choiceList.size(); t++) {
                        if (bean.getGoods_id().equals(choiceList.get(t).getGoods_id())) {
                            if ("2".equals(bean.getAttribute_state())) {
                                if (bean.getSku_id().equals(choiceList.get(t).getSku_id())) {
                                    index = t;
                                    break;
                                }
                            } else {
                                index = t;
                                break;
                            }
                        }
                    }
                    choiceList.set(index, bean);
                    purchaseRefundAddingAdapter.notifyDataSetChanged();
                    break;
            }
        }
        LogUtil.i("onActivityResult.notInIdArr的長度：" + notInIdArr.size());

    }

    // 根據條形碼查找列表中的貨物
    private void searchGoodbyCode(ArrayList<GoodsStoreRetreatInfo.DataBean> DataList, String info) {
        int i = -1;
        for (GoodsStoreRetreatInfo.DataBean parcelData : DataList) {
            if (info.equals(parcelData.getGoods_code())) {
                i = DataList.indexOf(parcelData);
                break;
            }
        }
        if (i < DataList.size() && i >= 0) {
            scrollToItem(i);
        } else {
            Toast.makeText(this, "列表中沒有該貨物", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 獲取採購倉與供貨商信息
     */
    private void getSupplierAndWarehouseInfo() {
        String url = "";
        if (userType.equals("1")) {
            url = Common.INFO_STORE_AND_WAREHOUSE_1;
        } else if (userType.equals("2")) {
            url = Common.INFO_STORE_AND_WAREHOUSE_2;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                storeWarehouseInfo = GsonUtils.JsonToBean(text, StoreWarehouseInfo.class);
                if (storeWarehouseInfo.getStatus() == 1) {
                    if (sprSupplierNameList.size() == 2)
                        sprSupplierNameList.remove(1);
                    for (int i = 0; i < storeWarehouseInfo.getSupplierList().size(); i++) {
                        sprSupplierIdList.add(storeWarehouseInfo.getSupplierList().get(i).getId());
                        sprSupplierNameList.add(storeWarehouseInfo.getSupplierList().get(i).getSupplier_name());
                    }

                    if (sprWarehouseNameList.size() == 2)
                        sprWarehouseNameList.remove(1);
                    for (int i = 0; i < storeWarehouseInfo.getWarehouseList().size(); i++) {
                        sprWarehouseIdList.add(storeWarehouseInfo.getWarehouseList().get(i).getId());
                        sprWarehouseNameList.add(storeWarehouseInfo.getWarehouseList().get(i).getName());
                    }
                    mHandler.sendEmptyMessage(GET_INFO_STOREWAREHOUSE);
                } else {
                    mHandler.sendEmptyMessage(GET_ERROR_STATUS);
                    Toast.makeText(PurchaseRefundAddingActivity.this, "暫無信息", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
//                    loadingDialog.dismiss();
            }
        });
    }

    /* 上傳退貨列表*/
    private void postRetreatOrder() {
        loadingDialog.show();
        String url = "";
        if (userType.equals("1")) {
            url = Common.GOODS_STORE_RETREAT_ACTION_1;
        } else if (userType.equals("2")) {
            url = Common.GOODS_STORE_RETREAT_ACTION_2;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            jsonObject.put("user_type", userType);
            jsonObject.put("goodsList", new Gson().toJson(choiceList));
            jsonObject.put("supplier_id", this_SupplierId);
            jsonObject.put("warehouse_id", this_WarehouseId);
            jsonObject.put("remarks", this_Remark);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                StatusBean data = GsonUtils.json2Bean(text, StatusBean.class);
                if (data.getStatus() == 1) {
                    choiceList.clear();
                    notInIdArr.clear();
                }
                loadingDialog.dismiss();
                Toast.makeText(PurchaseRefundAddingActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                mHandler.sendEmptyMessage(REFRESH_VIEW);
            }

            @Override
            protected void onFailure(ResponseException e) {
                LogUtil.i("網絡出錯");
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (choiceList.size() != 0)
            groupRemark.setVisibility(View.VISIBLE);
        else
            groupRemark.setVisibility(View.GONE);
    }


    @Override
    public void finish() {
        Intent intent = new Intent(this, PurchaseRefundActivity.class);
        intent.putExtra("refresh", true);
        setResult(RESULT_OK, intent);
        super.finish();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, PurchaseRefundActivity.class);
        intent.putExtra("refresh", true);
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }

    // 列表中搜索
    private void searchGood(String keyword) {
        int n = -1;
        for (GoodsStoreRetreatInfo.DataBean parcelData : choiceList) {
            if (parcelData.getGoods_name().contains(keyword)
                    || parcelData.getGoodsNumByAttr().contains(keyword)
                    || parcelData.getGoodsCodeByAttr().contains(keyword)) {
                n = choiceList.indexOf(parcelData);
                break;
            }
        }
        if (n < 0 || n >= choiceList.size()) {
            Toast.makeText(this, "列表中沒有該貨物", Toast.LENGTH_SHORT).show();
        } else {
            scrollToItem(n);
        }
    }

    //    跳轉到指定位置
    private void scrollToItem(int n) {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) rvPurRefundSetting.getLayoutManager();
        int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = linearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            rvPurRefundSetting.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = rvPurRefundSetting.getChildAt(n - firstItem).getTop();
            rvPurRefundSetting.scrollBy(0, top);
        } else {
            rvPurRefundSetting.scrollToPosition(n);
        }
    }
}
